package com.bmps.springcloud.insuredmicroservice.util.cloudplatform;

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;


/**
 * @author lazasha
 * @date 2019/7/24 10:20
 */
@Component
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate() {
        try {
            PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
            //连接池最大并发连接数
            poolingHttpClientConnectionManager.setMaxTotal(500);
            //单路由最大并发数
            poolingHttpClientConnectionManager.setDefaultMaxPerRoute(250);

            CloseableHttpClient httpClient = HttpClients.custom()
                    .setConnectionManager(poolingHttpClientConnectionManager)
                    .build();

            HttpComponentsClientHttpRequestFactory requestFactory =
                    new HttpComponentsClientHttpRequestFactory();

            requestFactory.setHttpClient(httpClient);
            requestFactory.setConnectionRequestTimeout(1000);

            requestFactory.setReadTimeout(3000);
            requestFactory.setConnectTimeout(1000);

            return new RestTemplate(requestFactory);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
